package com.cdshangpai.photoapp.ui.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSONObject;
import com.cdshangpai.photoapp.LogConfig;
import com.cdshangpai.photoapp.MainActivity;
import com.cdshangpai.photoapp.adapters.DataBean;
import com.cdshangpai.photoapp.databinding.MainFragmentBinding;
import com.cdshangpai.photoapp.ui.LoveActivity;
import com.cdshangpai.photoapp.ui.ServiceActivity;
import com.cdshangpai.photoapp.ui.caseui.CaseDetailActivity;
import com.cdshangpai.photoapp.ui.caseui.CaseMainActivity;
import com.cdshangpai.photoapp.ui.hotal.HotalDetailActivity;
import com.cdshangpai.photoapp.ui.hotal.HotalListActivity;
import com.cdshangpai.utils.db.AboutusDb;
import com.cdshangpai.utils.db.CaseDb;
import com.cdshangpai.utils.db.beans.Aboutus;
import com.cdshangpai.utils.db.beans.Account;
import com.cdshangpai.utils.db.beans.Case;
import com.cdshangpai.utils.offlinecache.CacheManager;
import com.cdshangpai.utils.offlinecache.aboutus.AboutusCacheProcessor;
import com.cdshangpai.utils.offlinecache.aboutus.NotifyUpdate;
import com.cdshangpai.utils.storage.ImageManager;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;

import java.util.ArrayList;
import java.util.List;

public class MainFragment extends Fragment {
    MainFragmentBinding binding;
    public String name="";
    AboutusDb aboutusDb;
    ImageManager imageManager;
    BannerImageAdapter adapter;

    public static long fiveFromTime=0L;
    public static Integer fiveNum=0;
    public static long fiveTimeLen=1000*2;

    private String[] ids=new String[0];
    private CaseDb caseDb;

    public void fiveClick()
    {
        boolean invalid=false;
        if(fiveFromTime==0L)
        {
            invalid=true;
        }else
        {
            long now=System.currentTimeMillis();
            if(now-fiveFromTime<fiveTimeLen&&fiveNum<5)
            {
                invalid=true;
            }
        }

        if(!invalid)
        {
            fiveFromTime=System.currentTimeMillis();
            fiveNum=1;
            return;
        }

        fiveNum++;
        if(fiveNum==5)
        {
            showUpdateMsg();
            //有效五连击
            fiveFromTime=System.currentTimeMillis();
            fiveNum=0;

            Log.i(LogConfig.logTag,"有效5连击");
            //立即同步服务器数据
            CacheManager.next();
        }
    }

    private void showUpdateMsg()
    {
        binding.setShowUpdateMsg(true);
        if(CacheManager.updateing)
        {
            binding.setUpdateMsg("更新中…");
        }
        else
        {
            binding.setUpdateMsg("开始强制更新…");
        }
        CountDownTimer timer = new CountDownTimer(3*1000, 3*1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.setShowUpdateMsg(false);
                    }
                });
            }
        }.start();
    }

    //后台关于我们下载完成后，通知跟新页面
    NotifyUpdate notifyUpdate=new NotifyUpdate() {
        @Override
        public void notifyUpdate() {
            syncLoadBannerData();
            Log.i(LogConfig.logTag,"notify update ui...");
        }
    };

    public MainFragment()
    {
        caseDb=new CaseDb();
        aboutusDb=new AboutusDb();
        imageManager=new ImageManager();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding= MainFragmentBinding.inflate(inflater);
        binding.setShowWarning(false);
        binding.setShowUpdateMsg(false);
        binding.setView(this);

        View view=binding.getRoot();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        setAccountName();
        syncLoadBannerData();
        Log.i(LogConfig.logTag,"onresume");
        AboutusCacheProcessor.registNotifyUpdate(notifyUpdate);
    }

    @Override
    public void onPause() {
        super.onPause();
        AboutusCacheProcessor.unregistNotifyUpdate();
        Log.i(LogConfig.logTag,"onpause");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden)
        {
            Log.i(LogConfig.logTag,"显示主页，加载banner数据");
            syncLoadBannerData();

            AboutusCacheProcessor.registNotifyUpdate(notifyUpdate);

            Log.i(LogConfig.logTag,"onshow");
        }
        else
        {
            AboutusCacheProcessor.unregistNotifyUpdate();
            Log.i(LogConfig.logTag,"onhide");
        }
    }

    /**
     * 初始化banner视图
     */
    private void initBannerView()
    {
        List<DataBean> images=new ArrayList<>();
        adapter = new BannerImageAdapter<DataBean>(images) {
            @Override
            public void onBindView(BannerImageHolder holder, DataBean data, int position, int size) {
                Bitmap temp = imageManager.loadImageToBitmap(data.imageUrl);
                Bitmap bitmap=imageManager.scale(temp,2560);
                holder.imageView.setImageBitmap(bitmap);
                holder.imageView.setLongClickable(true);
                holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                holder.imageView.setTag(position);

                holder.imageView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int position=new Integer(v.getTag().toString());
                        gotoCase(position);
                        return false;
                    }
                });
            }
        };
        binding.mainBanner.setAdapter(adapter);
    }

    //跳转到案例
    private void gotoCase(int position)
    {
        if(position<ids.length)
        {
            String id=ids[position];
            if(!TextUtils.isEmpty(id)) {
                Case cas = caseDb.queryById(Integer.parseInt(id));
                if(cas!=null) {
                    String caseString = JSONObject.toJSONString(cas);

                    Intent intent = new Intent(getContext(), CaseDetailActivity.class);
                    intent.putExtra("param", caseString);
                    startActivity(intent);
                    Log.i(LogConfig.logTag,"跳转到案例");
                }
            }
        }
    }

    private void syncLoadBannerData()
    {
        if(adapter==null)
        {
            initBannerView();
        }

        new Thread(){
            @Override
            public void run() {
                loadBannerData();
            }
        }.start();
    }

    //加载首页banner数据
    private void loadBannerData()
    {
        Aboutus aboutus=aboutusDb.queryBean();
        if(aboutus==null|| TextUtils.isEmpty(aboutus.homephotos))
        {
            return;
        }

        String[] photos=aboutus.homephotos.split(",");
        if(!TextUtils.isEmpty(aboutus.content))
        {
            ids=aboutus.content.split(",");
        }
        List<DataBean> images=new ArrayList<>();
        for(String photo:photos)
        {
            DataBean dataBean=new DataBean();
            dataBean.imageUrl=photo;
            images.add(dataBean);
        }


        Log.i(LogConfig.logTag,"准备显示banner数据"+aboutus.homephotos);
        setBannerData(images);
    }

    /**
     * 设置banner显示数据
     */
    private void setBannerData(List<DataBean> images)
    {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.setDatas(images);
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    public void setAccountName()
    {
        if(binding==null)
        {
            return;
        }
        Account account=LoginFragment.pickCacheAccount();
        if(account!=null)
        {
            name=account.name;
            binding.setName(name);
        }
        else
        {
            binding.setName("");
        }
    }

    /**
     * 退出前先确认一次
     */
    public void logout(){
        /*AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("你确认要退出吗?")
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                dologout();
                            }
                        }).setNegativeButton("取消", null);
        AlertDialog alert = builder.create();
        alert.show();*/
        binding.setShowWarning(true);
    }

    public void dologout()
    {
        CaseDetailActivity.clearSelected();
        HotalDetailActivity.cleanSelected();
        LoginFragment.logout();
        LoveActivity.cleanContent();
        MainActivity mainActivity=(MainActivity)getActivity();
        mainActivity.switchFragment();
    }

    public void gotoActitvity(String name)
    {
        Activity activity=getActivity();
        Class clz=Object.class;
        switch (name) {
            case "service":
                clz= ServiceActivity.class;
                break;
            case "case":
                clz= CaseMainActivity.class;
                break;
            case "hotal":
                clz= HotalListActivity.class;
                break;
            case "love":
                clz= LoveActivity.class;
                break;
        }
        Intent intent=new Intent(activity,clz);
        getActivity().startActivity(intent);
    }

    public void cancelLogout(){
        binding.setShowWarning(false);
    }

    public  void sureLogout(){
        cancelLogout();
        dologout();
    }
}
